<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    Bloom algorithm from: https://learnopengl.com/#!Advanced-Lighting/Bloom
 -->
<html>
<head>
    <title>PicoGL.js: Bloom</title>
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
    <style>
        #bloom-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Bloom
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/bloom.html">Source code</a>
        </div>
    </div>
    <div id="bloom-controls">
        Enable Bloom: <input id="bloom-toggle" type="checkbox" checked>
    </div>
    <canvas id="gl-canvas"></canvas>
    <script type="x-shader/vs" id="vertex-cube">
        #version 300 es

        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec4 normal;
        
        layout(std140) uniform SceneUniforms {
            uniform mat4 uViewProj;
            uniform vec4 eyePosition;
            uniform vec4 lightPosition;
            uniform vec4 lightColor;
            uniform vec4 lightPosition2;
            uniform vec4 lightColor2;
        };

        uniform mat4 uModel;
        
        out vec3 vPosition;
        out vec2 vUV;
        out vec3 vNormal;
        void main() {
            vec4 worldPosition = uModel * position;
            vPosition = worldPosition.xyz;
            vUV = uv;
            vNormal = (uModel * normal).xyz;
            gl_Position = uViewProj * worldPosition;
        }
    </script>
    <script type="x-shader/vf" id="fragment-cube">
        #version 300 es
        precision highp float;

        layout(std140) uniform SceneUniforms {
            uniform mat4 uViewProj;
            uniform vec4 eyePosition;
            uniform vec4 lightPosition;
            uniform vec4 lightColor;
            uniform vec4 lightPosition2;
            uniform vec4 lightColor2;
        };

        uniform sampler2D tex;
        
        in vec3 vPosition;
        in vec2 vUV;
        in vec3 vNormal;
        
        layout(location=0) out vec4 fragColor;
        layout(location=1) out vec4 bloom;
        void main() {
            vec3 color = texture(tex, vUV).rgb;

            vec3 normal = normalize(vNormal);
            vec3 eyeVec = normalize(eyePosition.xyz - vPosition);
            vec3 incidentVec = normalize(vPosition - lightPosition.xyz);
            vec3 lightVec = -incidentVec;
            float diffuse = max(dot(lightVec, normal), 0.0);
            float highlight = pow(max(dot(eyeVec, reflect(incidentVec, normal)), 0.0), 100.0);
            vec3 light = lightColor.rgb * (diffuse + highlight);

            incidentVec = normalize(vPosition - lightPosition2.xyz);
            lightVec = -incidentVec;
            diffuse = max(dot(lightVec, normal), 0.0);
            highlight = pow(max(dot(eyeVec, reflect(incidentVec, normal)), 0.0), 100.0);
            light += lightColor2.rgb * (diffuse + highlight);
            light += 0.1;

            fragColor = vec4(color * light, 1.0);
            if (dot(fragColor.rgb, vec3(0.2126, 0.7152, 0.0722)) > 1.0) {
                bloom = fragColor;
            }
        }
    </script>
    <script type="x-shader/vs" id="vertex-sun">
        #version 300 es

        layout(location=0) in vec4 position;

        layout(std140) uniform SunUniforms {
            mat4 uMVP;
            vec4 uColor;
        };
        
        void main() {
            gl_Position = uMVP * position;
        }
    </script>
    <script type="x-shader/vf" id="fragment-sun">
        #version 300 es
        precision highp float;

        layout(std140) uniform SunUniforms {
            mat4 uMVP;
            vec4 uColor;
        };

        layout(location=0) out vec4 fragColor;
        layout(location=1) out vec4 bloom;    
        void main() {
            fragColor = vec4(uColor.rgb, 1.0);
            bloom = vec4(uColor.rgb, 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-quad">
        #version 300 es

        layout(location=0) in vec4 position;

        void main() {
            gl_Position = position;
        }
    </script>
    <script type="x-shader/fs" id="fragment-blur">
        #version 300 es

        precision highp float;

        uniform ivec2 uTexelOffset;
        uniform sampler2D uTexture;

        out vec4 fragColor;
        void main() {
            ivec2 resolution = textureSize(uTexture, 0);

            float blurWeights[5];
            blurWeights[0] = 0.227027;
            blurWeights[1] = 0.1945946;
            blurWeights[2] = 0.1216216;
            blurWeights[3] = 0.054054;
            blurWeights[4] = 0.016216;

            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            
            vec3 color = vec3(0.0);
            for (int i = 0; i < 5; ++i) {
                ivec2 lowSampleCoord = clamp(fragCoord - uTexelOffset * i, ivec2(0), resolution);
                ivec2 highSampleCoord = clamp(fragCoord + uTexelOffset * i, ivec2(0), resolution);
                color += texelFetch(uTexture, lowSampleCoord, 0).rgb * blurWeights[i];
                color += texelFetch(uTexture, highSampleCoord, 0).rgb * blurWeights[i];
            }

            fragColor = vec4(color, 1.0);
        }
    </script>
    <script type="x-shader/fs" id="fragment-blend">
        #version 300 es

        precision highp float;

        uniform sampler2D uColor;
        uniform sampler2D uBloom;
        
        out vec4 fragColor;
        void main() {
            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            fragColor = texelFetch(uColor, fragCoord, 0) + texelFetch(uBloom, fragCoord, 0);
        }
    </script>
    <script>
        utils.addTimerElement();   
        
        var bloomEnabled = true;

        document.getElementById("bloom-toggle").addEventListener("change", function() {
            bloomEnabled = this.checked;
        });

        var canvas = document.getElementById("gl-canvas");

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var hTexelOffset = new Int32Array([1, 0]);
        var vTexelOffset = new Int32Array([0, 1]);

        var app = PicoGL.createApp(canvas)
        .clearColor(0.0, 0.0, 0.0, 1.0)
        .depthTest()
        .floatRenderTargets();

        if (!utils.testExtension("EXT_color_buffer_float")) {
            document.body.innerHTML = "This example requires extension EXT_color_buffer_float which is not supported on this system."
        }

        var timer = app.createTimer();

        var resolution = new Int32Array([app.width, app.height]);

        // SET UP PROGRAMS

        var cubeVsSource =  document.getElementById("vertex-cube").text.trim();
        var cubeFsSource =  document.getElementById("fragment-cube").text.trim();
        var cubeProgram = app.createProgram(cubeVsSource, cubeFsSource);

        var sunVsSource =  document.getElementById("vertex-sun").text.trim();
        var sunFsSource =  document.getElementById("fragment-sun").text.trim();
        var sunProgram = app.createProgram(sunVsSource, sunFsSource);

        var quadVsSource =  document.getElementById("vertex-quad").text.trim();
        var quadVertexShader = app.createShader(PicoGL.VERTEX_SHADER, quadVsSource);

        var blurFsSource =  document.getElementById("fragment-blur").text.trim();
        var blurProgram = app.createProgram(quadVertexShader, blurFsSource);

        var blendFsSource =  document.getElementById("fragment-blend").text.trim();
        var blendProgram = app.createProgram(quadVertexShader, blendFsSource);

        quadVertexShader.delete();

        // SET UP FRAMEBUFFERS AND TEXTURES

        var colorTarget1 = app.createTexture2D(null, app.width, app.height, { type: PicoGL.FLOAT });
        var colorTarget2 = app.createTexture2D(null, app.width, app.height, { type: PicoGL.FLOAT });
        var depthTarget = app.createRenderbuffer(app.width, app.height, PicoGL.DEPTH_COMPONENT16 );

        var colorBuffer = app.createFramebuffer()
        .colorTarget(0, colorTarget1)
        .colorTarget(1, colorTarget2)
        .depthTarget(depthTarget);
        
        var blurTarget = app.createTexture2D(null, app.width, app.height, { type: PicoGL.FLOAT });
        
        var blurBuffer = app.createFramebuffer()
        .colorTarget(0, blurTarget);
        
        var bloomTarget = app.createTexture2D(null, app.width, app.height, { type: PicoGL.FLOAT });

        var bloomBuffer = app.createFramebuffer()
        .colorTarget(0, bloomTarget);

        var blankTexture = app.createTexture2D(null, 1, 1);

        // SET UP GEOMETRY

        var cube = utils.createBox({dimensions: [1.0, 1.0, 1.0]})
        var cubePositions = app.createVertexBuffer(PicoGL.FLOAT, 3, cube.positions);
        var cubeUVs = app.createVertexBuffer(PicoGL.FLOAT, 2, cube.uvs);
        var cubeNormals = app.createVertexBuffer(PicoGL.FLOAT, 3, cube.normals);

        var cubeArray = app.createVertexArray()
        .vertexAttributeBuffer(0, cubePositions)
        .vertexAttributeBuffer(1, cubeUVs)
        .vertexAttributeBuffer(2, cubeNormals);

        var sun = utils.createSphere({radius: 0.1});
        var sunPositions = app.createVertexBuffer(PicoGL.FLOAT, 3, sun.positions);
        var sunIndices = app.createIndexBuffer(PicoGL.UNSIGNED_SHORT, 3, sun.indices);

        var sunArray = app.createVertexArray()
        .vertexAttributeBuffer(0, sunPositions)
        .indexBuffer(sunIndices);

        var quadPositions = app.createVertexBuffer(PicoGL.FLOAT, 2, new Float32Array([
            -1, 1,
            -1, -1,
            1, -1,
            -1, 1,
            1, -1,
            1, 1,
        ]));

        var quadArray = app.createVertexArray().vertexAttributeBuffer(0, quadPositions);


        // SET UP OTHER DATA

        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(1, 1, 1);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var cube = {
            rotation: vec3.create(),
            modelMatrix: mat4.create(),
            mvpMatrix: mat4.create()
        };

        var suns = [
            {
                position: vec3.fromValues(0.7, 0.75, 0.3),
                color: vec3.fromValues(1, 1, 1),
                modelMatrix: mat4.create(),
                mvpMatrix: mat4.create(),
                uniforms: app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_VEC4,
                ])
            },
            {
                position: vec3.fromValues(-4, -1.5, -2),
                color: vec3.fromValues(0, 0, 1),
                modelMatrix: mat4.create(),
                mvpMatrix: mat4.create(),
                uniforms: app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_VEC4,
                ])
            }

        ];

        utils.xformMatrix(suns[0].modelMatrix, suns[0].position, null, null);
        mat4.multiply(suns[0].mvpMatrix, viewProjMatrix, suns[0].modelMatrix);
        suns[0].uniforms.set(0, suns[0].mvpMatrix)
        .set(1, suns[0].color)
        .update();

        utils.xformMatrix(suns[1].modelMatrix, suns[1].position, null, vec3.fromValues(30, 30, 30));
        mat4.multiply(suns[1].mvpMatrix, viewProjMatrix, suns[1].modelMatrix);
        suns[1].uniforms.set(0, suns[1].mvpMatrix)
        .set(1, suns[1].color)
        .update();

        var sceneUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .set(2, suns[0].position)
        .set(3, suns[0].color)
        .set(4, suns[1].position)
        .set(5, suns[1].color)
        .update();

        utils.loadImages(["img/webgl-logo.png"], function(images) {
            // CREATE TEXTURE
            var texture = app.createTexture2D(images[0], { flipY: true });

            // PREPARE DRAW CALLS
            var drawCall = app.createDrawCall(cubeProgram, cubeArray)
            .uniformBlock("SceneUniforms", sceneUniforms)
            .texture("tex", texture);

            var sunDrawCall = app.createDrawCall(sunProgram, sunArray)
            .uniformBlock("SunUniforms", suns[0].uniforms);

            var sun2DrawCall = app.createDrawCall(sunProgram, sunArray)
            .uniformBlock("SunUniforms", suns[1].uniforms);
    
            var hBlurDrawCall = app.createDrawCall(blurProgram, quadArray)
            .uniform("uTexelOffset", hTexelOffset)
            .texture("uTexture", colorBuffer.colorAttachments[1]);

            var vBlurDrawCall = app.createDrawCall(blurProgram, quadArray)
            .uniform("uTexelOffset", vTexelOffset)
            .texture("uTexture", blurBuffer.colorAttachments[0]);

            var blendDrawCall = app.createDrawCall(blendProgram, quadArray)
            .texture("uColor", colorBuffer.colorAttachments[0])
            .texture("uBloom", bloomBuffer.colorAttachments[0]);

            // TEXTURES FOR PING PONGING THE BLUR
            var blurTextureA = colorBuffer.colorAttachments[1];
            var blurTextureB = bloomBuffer.colorAttachments[0];
            var blurReadTexture = blurTextureA;
            var blurWriteTexture = blurTextureB;

            window.onresize = function() {
                app.resize(window.innerWidth, window.innerHeight);
                colorBuffer.resize();
                blurBuffer.resize();
                bloomBuffer.resize();

                // Make sure both targets are correct size.
                blurTextureA.resize(app.width, app.height);
                blurTextureB.resize(app.width, app.height);

                mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);
                mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
                sceneUniforms.set(0, viewProjMatrix).update(0);

                mat4.multiply(suns[0].mvpMatrix, viewProjMatrix, suns[0].modelMatrix);
                suns[0].uniforms.set(0, suns[0].mvpMatrix).update(0);

                mat4.multiply(suns[1].mvpMatrix, viewProjMatrix, suns[1].modelMatrix);
                suns[1].uniforms.set(0, suns[1].mvpMatrix).update(0);
            }

            function draw() {
                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }

                timer.start();

                cube.rotation[0] += 0.01;
                cube.rotation[1] += 0.02;

                utils.xformMatrix(cube.modelMatrix, null, cube.rotation, null);
                drawCall.uniform("uModel", cube.modelMatrix);

                colorBuffer.colorTarget(1, blurReadTexture);


                app.drawFramebuffer(colorBuffer).clear();
                drawCall.draw();
                sunDrawCall.draw();
                sun2DrawCall.draw();

                if (bloomEnabled) {
                    for (var i = 0; i < 4; ++i) {
                        hBlurDrawCall.texture("uTexture", blurReadTexture);
                        bloomBuffer.colorTarget(0, blurWriteTexture);

                        app.drawFramebuffer(blurBuffer).clear();
                        hBlurDrawCall.draw()

                        app.drawFramebuffer(bloomBuffer).clear();
                        vBlurDrawCall.draw();

                        if (blurReadTexture === blurTextureA) {
                            blurReadTexture = blurTextureB;
                            blurWriteTexture = blurTextureA;
                        } else {
                            blurReadTexture = blurTextureA;
                            blurWriteTexture = blurTextureB;
                        }
                    }

                    blendDrawCall.texture("uBloom", blurWriteTexture);
                } else {
                    blendDrawCall.texture("uBloom", blankTexture);
                }

                

                app.defaultDrawFramebuffer().clear();
                blendDrawCall.draw();
                
                timer.end();

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        });

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
